var bookmarksImpUtils = require('../utils/explorer.bookmarks.import.utils');
var defaultBookmarks = require('../utils/default.bookmarks.data');
var UserFavorite = require('../utils/user.favorite.utils');
var favoriteDb = require('../utils/database.dao.utils');
var dateconvert = require('../utils/date.convert.utils');
var encryption = require('../utils/encryption.utils');
var msgCode = require('../utils/constant.msg.code');
var token = require('../utils/token.utils');
var express = require('express');
var _ = require('underscore');
var router = express.Router();
var path = require('path');
var zlib = require('zlib');
var fs = require('fs');

module.exports = router;

// 首页
router.get('/', function (req, res) {
  //favoriteDb.insert(defaultBookmarks,function(err,data){
  //  if(err) console.log(err);
  //  console.dir(data);
  //});
  //new UserFavorite('wuqinglong','wuqinglong').login();
  //bookmarksImpUtils('f:/Bookmarks.txt', function () {
  //  console.log('------------111-----------')
  //});
  res.render('index');
});

// 获取收藏夹数据
router.get('/favorite', function (req, res) {
  var loginInfo = token.getToken(req);
  favoriteDb.find({user: loginInfo.user, pass: loginInfo.pass}, function (err, data) {
    if (data && data[0] && 'bookmarks' in data[0]) {
      res.send(JSON.stringify(data[0].bookmarks));
    } else {// no any bookmark
      favoriteDb.find({user: '', pass: ''}, function (err, data) {
        if (data && data[0] && 'bookmarks' in data[0]) {
          res.send(JSON.stringify(data[0].bookmarks));
        } else {
          res.send('[]');
        }
      });
    }
  });
});

// 获取模板
router.get('/template/:name', function (req, res) {
  var templatePath = path.join(__dirname, '../views') + '/' + req.params.name;
  fs.readFile(templatePath, 'utf-8', function (err, data) {
    res.send(err ? '' : data.replace(/[\t\r\n]+| {2,}/g, ''));
  });
});

// 注册
router.post('/reg', function (req, res) {
  var msg = {}, name = req.param('name'), pwd = req.param('pwd');
  if (!name) {
    msg['name'] = msgCode.MSG.NAME_NULL;
  } else if (name.length > 100) {
    msg['name'] = msgCode.MSG.NAME_VALIDATE_ERROR;
  }
  if (!pwd) {
    msg['pwd'] = msgCode.MSG.PWD_NULL;
  } else if (pwd.length > 100 || pwd.length < 5) {
    msg['pwd'] = msgCode.MSG.PWD_VALIDATE_ERROR;
  }
  if ('name' in msg || 'pwd' in msg) {
    res.send(JSON.stringify({code: msgCode.ERR, msg: msg}));
    return;
  }
  favoriteDb.find({user: name}, {user: 1}, function (err, data) {
    if (err) {
      res.send(JSON.stringify({code: msgCode.ERR, msg: err}));
    } else if (data.length) {// exists
      res.send(JSON.stringify({code: msgCode.ERR, msg: msgCode.MSG.NAME_LOGIN_EXISTS}));
    } else {
      favoriteDb.insert({user: name, pass: encryption.md5(pwd)}, function (err, data) {
        res.send(err ? JSON.stringify({code: msgCode.ERR, msg: err}) :
          JSON.stringify({code: msgCode.OK, msg: token.create(req)}));
      });
    }
  });
});

// 登录
router.post('/login', function (req, res) {
  var msg = {}, name = req.param('name'), pwd = req.param('pwd');
  if (!name) {
    msg['name'] = msgCode.MSG.NAME_NULL;
  }
  if (!pwd) {
    msg['pwd'] = msgCode.MSG.PWD_NULL;
  }
  if ('name' in msg || 'pwd' in msg) {
    res.send(JSON.stringify({code: msgCode.ERR, msg: msg}));
    return;
  }
  favoriteDb.find({user: name}, {user: 1}, function (err, data) {
    if (err) {
      res.send(JSON.stringify({code: msgCode.ERR, msg: err}));
    } else if (data.length) {// name exists
      favoriteDb.find({user: name, pass: encryption.md5(pwd)}, {user: 1}, function (err, data) {
        if (err) {
          res.send(JSON.stringify({code: msgCode.ERR, msg: err}));
        } else if (data.length) {// name pwd exists
          res.send(JSON.stringify({code: msgCode.OK, msg: token.create(req)}));
        } else {
          res.send(JSON.stringify({code: msgCode.ERR, msg: msgCode.MSG.PWD_LOGIN_ERROR}));
        }
      });
    } else {
      res.send(JSON.stringify({code: msgCode.ERR, msg: msgCode.MSG.NAME_LOGIN_ERROR}));
    }
  });
});

// 持久化
router.delete('/save/:_token/:id', function (req, res) {
  var id = req.params.id, loginInfo = token.getToken(req);
  if (!loginInfo.user || !loginInfo.pass) {
    res.send(JSON.stringify({code: msgCode.ERR, msg: msgCode.MSG.NEED_LOGIN}));
    return;
  }
  if (!id) {
    res.send(JSON.stringify({code: msgCode.ERR, msg: msgCode.MSG.ID_NULL}));
    return;
  }
  favoriteDb.find({
    user: loginInfo.user,
    pass: loginInfo.pass,
    bookmarks: {$elemMatch: {id: parseInt(id, 10)}}
  }, {_id: 1}, function (err, data) {
    if (err) {
      res.send(JSON.stringify({code: msgCode.ERR, msg: err}));
    } else if (data.length) {
      favoriteDb.update({
        user: loginInfo.user,
        pass: loginInfo.pass
      }, {$pull: {bookmarks: {id: parseInt(id, 10)}}}, function (err, data) {
        res.send(err ? JSON.stringify({code: msgCode.ERR, msg: err}) : JSON.stringify({code: msgCode.OK}));
      });
    } else {
      res.send(JSON.stringify({code: msgCode.ERR, msg: msgCode.MSG.NO_DATA}));
    }
  });
});

router.put('/save/:id', function (req, res) {
  var msg = {}, id = req.params.id, url = req.param('url'), name = req.param('name'), tag = req.param('tag');
  if (url && url.length > 100) {
    msg['url'] = msgCode.MSG.URL_VALIDATE_ERROR;
  }
  if (name && name.length > 100) {
    msg['name'] = msgCode.MSG.NAME_VALIDATE_ERROR;
  }
  if (tag && !_.isArray(tag)) {
    tag = [tag];
  }
  if (tag) {
    tag.forEach(function (e, i) {
      tag[i] = tag[i].toLowerCase();
      if (e.length > 100) {
        msg['tag'] = msgCode.MSG.TAG_VALIDATE_ERROR;
      }
    });
  }
  if (!name && !url && (!tag || tag.length === 0)) {
    res.send(JSON.stringify({code: msgCode.ERR, msg: msgCode.MSG.EDIT_NULL}));
    return;
  } else if ('name' in msg || 'url' in msg || 'tag' in msg) {
    res.send(JSON.stringify({code: msgCode.ERR, msg: msg}));
    return;
  }
  var loginInfo = token.getToken(req);
  if (!loginInfo.user || !loginInfo.pass) {
    res.send(JSON.stringify({code: msgCode.ERR, msg: msgCode.MSG.NEED_LOGIN}));
    return;
  }
  favoriteDb.find({
    user: loginInfo.user,
    pass: loginInfo.pass,
    bookmarks: {$elemMatch: {id: parseInt(id, 10)}}
  }, {_id: 1}, function (err, data) {
    if (err) {
      res.send(JSON.stringify({code: msgCode.ERR, msg: err}));
    } else if (data.length) {
      var data = {"$set": {}}, keys = ['name', 'url', 'tag'];
      [name, url, tag].forEach(function (e, i) {
        if (e)
          data["$set"]["bookmarks.$." + keys[i]] = e;
      });
      favoriteDb.update({
        user: loginInfo.user,
        pass: loginInfo.pass,
        "bookmarks.id": parseInt(id, 10)
      }, data, function (err, data) {
        res.send(err ? JSON.stringify({code: msgCode.ERR, msg: err}) : JSON.stringify({code: msgCode.OK}));
      });
    } else {
      res.send(JSON.stringify({code: msgCode.ERR, msg: msgCode.MSG.NO_DATA}));
    }
  });
});

router.post('/save', function (req, res) {
  var msg = {}, url = req.param('url'), name = req.param('name'), tag = req.param('tag') || [];
  if (!url) {
    msg['url'] = msgCode.MSG.URL_NULL;
  } else if (url.length > 100) {
    msg['url'] = msgCode.MSG.URL_VALIDATE_ERROR;
  }
  if (!name) {
    msg['name'] = msgCode.MSG.NAME_NULL;
  } else if (name.length > 100) {
    msg['name'] = msgCode.MSG.NAME_VALIDATE_ERROR;
  }
  if (tag && !_.isArray(tag)) {
    tag = [tag];
  }
  if (tag) {
    tag.forEach(function (e, i) {
      tag[i] = tag[i].toLowerCase();
      if (e.length > 100) {
        msg['tag'] = msgCode.MSG.TAG_VALIDATE_ERROR;
      }
    });
  }
  if ('name' in msg || 'url' in msg || 'tag' in msg) {
    res.send(JSON.stringify({code: msgCode.ERR, msg: msg}));
    return;
  }
  var loginInfo = token.getToken(req);
  if (!loginInfo.user || !loginInfo.pass) {
    res.send(JSON.stringify({code: msgCode.ERR, msg: msgCode.MSG.NEED_LOGIN}));
    return;
  }
  favoriteDb.find({
    user: loginInfo.user,
    pass: loginInfo.pass
  }, {_id: 1}, function (err, data) {
    if (err) {
      res.send(JSON.stringify({code: msgCode.ERR, msg: err}));
    } else if (data.length) {
      favoriteDb.update({
        user: loginInfo.user,
        pass: loginInfo.pass
      }, {
        $addToSet: {
          bookmarks: {
            name: name,
            url: url,
            tag: tag,
            id: !data[0].bookmarks.length ? 1 : (Math.max.apply(null, _.pluck(data[0].bookmarks, 'id')) + 1),
            time: dateconvert.toStr(new Date())
          }
        }
      }, function (err, data) {
        res.send(err ? JSON.stringify({code: msgCode.ERR, msg: err}) : JSON.stringify({code: msgCode.OK}));
      });
    } else {
      res.send(JSON.stringify({code: msgCode.ERR, msg: msgCode.MSG.NO_DATA}));
    }
  });
});